<template>
    <el-form
        ref="ruleForm"
        :model="formData"
        label-position="right"
        label-width="140px"
        inline
    >
        <el-form-item label="获奖机构">
            <el-input
                v-model="formData.researchOrgName"
                clearable
                disabled
            />
        </el-form-item>
        <el-form-item label="获得奖项：">
            <div v-for="(item, index) in trophy.rankList" :key="index" style="width: 80%;">
                {{ item.rankNameCn }}
            </div>
        </el-form-item>
        <el-form-item label="申请说明：">
            <el-input
                v-model="formData.applyExplain"
                placeholder="请输入申请说明"
                :rows="4"
                type="textarea"
                clearable
                disabled
            />
        </el-form-item>
        <el-form-item label="相关附件：">
            <img
                class="logo-box"
                :src="trophy.proxyResoucePath + trophy.logoInfo?.filePath"
                alt=""
                @click="DOWNLOAD_SINGLE + '?id=' + trophy.logo"
            />
        </el-form-item>
        <el-form-item label="申请审核意见：" prop="applyOpinion">
            <el-input
                v-model="formData.applyOpinion"
                placeholder="请输入申请审核意见"
                :rows="4"
                type="textarea"
                clearable
                :disabled="optType !== 1"
            />
        </el-form-item>
        <div v-if="optType == 1" class="box-wrap">
            <el-button type="primary" @click="handleSubmit(3)"> 发设计师制作 </el-button>
            <el-button type="primary" @click="handleSubmit(1)"> 发用户修改 </el-button>
            <el-button @click="handleCancel"> 取 消 </el-button>
        </div>
        <el-form-item v-if="optType >= 2" label="宣传图：">
            <el-upload
                v-if="optType == 2"
                v-model:file-list="fileList"
                :class="{hide_box: optType !== 2}"
                :data="{orgId: trophy.researchOrgId, fileType: 1, moduleType: 2}"
                :action="UPLOAD"
                :on-success="handleSuccess"
                :before-upload="beforeAvatarUpload"
                :limit="1"
                :on-exceed="handleExceed"
                :before-remove="beforeRemove"
            >
                <el-icon>
                    <el-button> <Plus /> 上传宣传图</el-button>
                </el-icon>
                <template #tip>
                    <div class="el-upload__tip hide_box">
                        最多上传1个附件
                    </div>
                </template>
            </el-upload>
            <a v-else :href="DOWNLOAD_SINGLE + `?id=` + fileList[0].fileId">{{ fileList[0].name }}</a>
        </el-form-item>
        <el-form-item v-if="optType == 2 && formData.auditOpinion" label="宣传图审核意见：" prop="auditOpinion">
            <el-input
                v-model="formData.auditOpinion"
                :rows="4"
                type="textarea"
                disabled
            />
        </el-form-item>
        <el-form-item v-if="optType == 2 && formData.revokeExplain" label="撤回说明：" prop="revokeExplain">
            <el-input
                v-model="formData.revokeExplain"
                :rows="4"
                type="textarea"
                disabled
            />
        </el-form-item>
        <div v-if="optType == 2" class="box-wrap">
            <el-button type="primary" @click="handleSubmit(4)"> 提交审核 </el-button>
            <el-button @click="handleCancel"> 取 消 </el-button>
        </div>

        <el-form-item v-if="optType >= 3" label="宣传图审核意见：" prop="auditOpinion">
            <el-input
                v-model="formData.auditOpinion"
                placeholder="请输入宣传图审核意见"
                :rows="4"
                type="textarea"
                clearable
                :disabled="optType !== 3"
            />
        </el-form-item>
        <el-form-item v-if="optType == 3 && formData.revokeExplain" label="撤回说明：" prop="revokeExplain">
            <el-input
                v-model="formData.revokeExplain"
                :rows="4"
                type="textarea"
                disabled
            />
        </el-form-item>
        <div v-if="optType == 3" class="box-wrap">
            <el-button type="primary" @click="handleSubmit(3)"> 发设计师制作 </el-button>
            <el-button type="primary" @click="handleSubmit(5)"> 发用户下载 </el-button>
            <el-button @click="handleCancel"> 取 消 </el-button>
        </div>

        <el-form-item v-if="optType >= 4" label="撤回说明：" prop="revokeExplain">
            <el-input
                v-model="formData.revokeExplain"
                placeholder="请输入撤回说明"
                :rows="4"
                type="textarea"
                clearable
                :disabled="optType !== 4"
            />
        </el-form-item>
        <div v-if="optType == 4" class="box-wrap">
            <el-button type="primary" @click="handleSubmit(4)"> 发管理员审核 </el-button>
            <el-button type="primary" @click="handleSubmit(3)"> 发设计师修改 </el-button>
            <el-button @click="handleCancel"> 取 消 </el-button>
        </div>
    </el-form>
    <!-- <div style="float: right;">
    <el-button @click="handleCancel"> 取 消 </el-button>
    <el-button type="primary" @click="handleSubmit"> 提 交 </el-button>
  </div> -->
</template>

<script lang="ts">
import { reactive, ref, toRefs, defineComponent, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import  { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { updateTrophyApi } from '@/api/admin'
import { assign, cloneDeep, omit, split, compact, pullAll, remove, map, join, size } from 'lodash-es'
import { UPLOAD, DOWNLOAD_SINGLE } from '@/api/file'

export default defineComponent({
    name: 'OtherOpt',
    props: {
        optType: {
            type: Number,
            default: 0
        },
        trophy: {
            type: Object,
            default: null
        },
        otherOptVisible: {
            type: Boolean
        }
    },
    emits: ['update:otherOptVisible'],
    setup(props, { attrs, emit }) {
        const router = useRouter()
        const ruleForm = ref<FormInstance>()
        // optType 1=资料审核  2=上传宣传图 3=宣传图审核  4=撤回宣传图
        const formData = ref(<
      {
        id: number
        researchOrgName: string
        applyExplain: string
        applyOpinion: string
        auditOpinion: string
        revokeExplain: string
        trophyLinks: string
        revokeStatus: number
      }
    >{
        id: 0,
        researchOrgName: '',
        applyExplain: '',
        applyOpinion: '',
        auditOpinion: '',
        revokeExplain: '',
        trophyLinks: '',
        revokeStatus: 1
    })
        // console.log('props.trophy--', props.trophy);
        formData.value = cloneDeep(props.trophy)
        const fileList = ref<UploadUserFile[]>(props.trophy.trophyLinkList)
        const trophyLinkArr = ref<[]>(map(fileList.value, function(n){return n.fileId}))
        const handleCancel = () => {
            emit('update:otherOptVisible', false)
        }
        const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
            // if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
            //   ElMessage.error('请上传 JPG｜JPEG 格式的文件!')
            //   return false
            // } 
            console.log('------', rawFile.size)

            if (rawFile.size / 1024 / 1024 > 20) {
                ElMessage.error('请上传小于20M的文件!')
                return false
            }
            return true
        }
        const handleSuccess: UploadProps['onSuccess'] = ( response, uploadFile) => {
            console.log('response==', response)
            console.log('uploadFile==', uploadFile)
            // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
            if(response.code === 200){
                trophyLinkArr.value.push(response.data.fileId)
                console.log('trophyLinkArr===', trophyLinkArr)

                // applyFormData.value.logo = response.data.filePath;
            }
        }
        const dialogImageUrl = ref('')
        const dialogVisible = ref(false)
        const handlePictureCardPreview = (file: UploadFile) => {
            dialogImageUrl.value = file.url!
            dialogVisible.value = true
        }
        const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
            return ElMessageBox.confirm(
                `确认删除 ${uploadFile.name} ?`
            ).then(
                () => {
                    trophyLinkArr.value = []
                    return true
                },
                () => false
            )
        }
        const handleDownload = (file: UploadFile) => {
            console.log(file)
            if(file.fileId){
                console.log('历史文件 ID===', file.fileId)
                location.href = DOWNLOAD_SINGLE + '?id=' + file.fileId
            }else{
                console.log('新文件 ID===', file.response.data.fileId)
            }
        }
        const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
            ElMessage.warning(
                `限制上传数量为 ${files.length} ，请删除已存在的文件，重新上传新文件`
            )
        }
        const handleRemove = (file: UploadFile) => {
            if(file.fileId){
                console.log('历史文件 ID===', file.fileId)
                pullAll(trophyLinkArr.value, [file.fileId])
                remove(fileList.value, function(n) {return n.fileId == file.fileId })
            }else{
                console.log('新文件 ID===', file.response.data.fileId)
                pullAll(trophyLinkArr.value, [file.response.data.fileId])
                remove(fileList.value, function(n) {
                    if(!n.fileId){
                        return n.response.data.fileId == file.response.data.fileId
                    }
                })
            }
            // console.log('trophyLinkArr-----', trophyLinkArr.value);
            // console.log('fileList-----', fileList);
        }
        // 保存提交
        const handleSubmit = (trophyStatus) => {
            let params = ref<any>({})
            // trophyStatus  1.未申请 2.已申请 3.待制作 4.待审核 5.已完成'
            if(props.optType == 1){
                // 流程变成：3.待制作
                if(trophyStatus == 3){
                    if(size(formData.value.applyOpinion) == 0){
                        ElMessage.warning('请输入申请审核意见!')
                        return false
                    }
                    params.value = { id: formData.value.id, applyOpinion: formData.value.applyOpinion, trophyStatus: trophyStatus }
                }else if(trophyStatus == 1){
                    if(size(formData.value.applyOpinion) == 0){
                        ElMessage.warning('请输入申请审核意见!')
                        return false
                    }
                    params.value = { id: formData.value.id, applyOpinion: formData.value.applyOpinion, trophyStatus: trophyStatus }
                }
            }else if(props.optType == 2){
                // 流程变成：4.待审核 
                console.log('trophyLinkArr.value', trophyLinkArr.value)
                if(size(trophyLinkArr.value) == 0){
                    ElMessage.warning('请上传宣传图文件！')
                    return false
                }
                params.value = { id: formData.value.id, trophyLinks: join(trophyLinkArr.value, ','), trophyStatus: trophyStatus }
            }else if(props.optType == 3){
                // 流程变成：5.已完成
                if(trophyStatus == 5){
                    if(size(formData.value.auditOpinion) == 0){
                        ElMessage.warning('请输入宣传图审核意见!')
                        return false
                    }
                    params.value = { id: formData.value.id, auditOpinion: formData.value.auditOpinion, trophyStatus: trophyStatus }
                }else if(trophyStatus == 3){
                    if(size(formData.value.auditOpinion) == 0){
                        ElMessage.warning('请输入宣传图审核意见!')
                        return false
                    }
                    params.value = { id: formData.value.id, auditOpinion: formData.value.auditOpinion, trophyStatus: trophyStatus }
                }
            }else if(props.optType == 4){
                if(size(formData.value.revokeExplain) == 0){
                    ElMessage.warning('请输入申撤回说明!')
                    return false
                }
                params.value = { id: formData.value.id, revokeExplain: formData.value.revokeExplain, trophyStatus: trophyStatus }
            }
            console.log('params.value----', params.value)
            updateTrophyApi(params.value).then((res) => {
                if(res*1 === 200)
                    ElMessage.success('编辑成功')
            })
            setTimeout(() => {
                router.go(0)
            }, 100)
        }
        return {
            formData,
            ruleForm,
            handleCancel,
            handleSubmit,
            handleExceed,
            beforeRemove,
            UPLOAD,
            beforeAvatarUpload,
            handleSuccess,
            dialogImageUrl,
            dialogVisible,
            handlePictureCardPreview,
            handleDownload,
            handleRemove,
            fileList,
            DOWNLOAD_SINGLE
        }
    }
})
</script>

<style scoped>
  :deep(.el-upload--picture-card){
    width: 100px;
    height: 100px;
  }
  :deep(.el-upload){
    width: 100px;
    margin-left: 8px;
    line-height: 100px;
  }

</style>
<style lang="scss" scoped>
  .box-wrap{
    text-align: center;
    margin-top: 22px;

    & > button {
      &:not(:first-child) {
        margin-left: 30px;
      }
    }
  }
</style>

<style scoped>
  .logo-box {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
</style>
